package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.core.enums.BorrowerStatusEnum;
import com.atguigu.srb.core.enums.IntegralEnum;
import com.atguigu.srb.core.mapper.BorrowerAttachMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.mapper.UserIntegralMapper;
import com.atguigu.srb.core.pojo.entity.Borrower;
import com.atguigu.srb.core.mapper.BorrowerMapper;
import com.atguigu.srb.core.pojo.entity.BorrowerAttach;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.entity.UserIntegral;
import com.atguigu.srb.core.pojo.vo.BorrowerApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerAttachVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.pojo.vo.BorrowerVO;
import com.atguigu.srb.core.service.BorrowerAttachService;
import com.atguigu.srb.core.service.BorrowerService;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author 龙龙龙
 * @since 2022-01-21
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {


    @Resource
    private UserIntegralMapper userIntegralMapper;


    @Resource
    private BorrowerAttachMapper borrowerAttachMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private BorrowerAttachService borrowerAttachService;

    @Autowired
    private DictService dictService;

    @Override
    public Integer getBorrowerStatus(Long userId) {
        QueryWrapper<Borrower> borrowerQueryWrapper = new QueryWrapper<>();
        borrowerQueryWrapper.select("status").eq("user_id", userId);
        List<Object> objects = baseMapper.selectObjs(borrowerQueryWrapper);
        if (objects.size() == 0) {
            //借款人尚未提交信息
            return BorrowerStatusEnum.NO_AUTH.getStatus();
        }
        Integer status = (Integer) objects.get(0);
        return status;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveBorrower(Long userId, BorrowerVO borrowerVO) {
        //1.保存borrower
        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(borrowerVO, borrower);
        //查到user的信息 填充到borrower表中
        UserInfo user = userInfoMapper.selectById(userId);

        borrower.setUserId(userId);
        borrower.setName(user.getName());
        borrower.setIdCard(user.getIdCard());
        borrower.setMobile(user.getMobile());
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());//认证中

        baseMapper.insert(borrower);

        //2.通过borrowerId 保存borrowerAttach
        //保存附件
        List<BorrowerAttach> borrowerAttachList = borrowerVO.getBorrowerAttachList();
        borrowerAttachList.forEach(borrowerAttach -> {
            borrowerAttach.setBorrowerId(borrower.getId());
            borrowerAttachMapper.insert(borrowerAttach);
        });


        //3.修改UserInfo表

        user.setBorrowAuthStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        userInfoMapper.updateById(user);
        return null;
    }

    @Override
    public IPage<Borrower> getList(Page<Borrower> pageParam, String keyword) {
        QueryWrapper<Borrower> queryWrapper = new QueryWrapper<>();

        //如果没有全部参数 查询全部
        if (StringUtils.isEmpty(keyword)) {
            return baseMapper.selectPage(pageParam, null);
        }

        queryWrapper.like("name", keyword)
                .or().like("mobile", keyword)
                .or().like("id_card", keyword).orderByDesc("id");

        Page<Borrower> borrowerPage = baseMapper.selectPage(pageParam, queryWrapper);

        return borrowerPage;
    }

    @Override
    public BorrowerDetailVO getBorrowerDetailVOById(Long id) {
        BorrowerDetailVO borrowerDetailVO = new BorrowerDetailVO();

        //查询借款人详情
        Borrower borrower = baseMapper.selectById(id);
        BeanUtils.copyProperties(borrower, borrowerDetailVO);
        //审批状态
        String status = BorrowerStatusEnum.getMsgByStatus(borrower.getStatus());
        borrowerDetailVO.setStatus(status);
        //身份证
        borrowerDetailVO.setIdCard(borrower.getIdCard());

        //婚否
        borrowerDetailVO.setMarry(borrower.getMarry() == 1 ? "是" : "否");
        //性别
        borrowerDetailVO.setSex(borrower.getSex() == 1 ? "男" : "女");

        //计算下拉列表选中内容
        String education = dictService.getNameByParentDictCodeAndValue("education", borrower.getEducation());
        String industry = dictService.getNameByParentDictCodeAndValue("moneyUse", borrower.getIndustry());
        String income = dictService.getNameByParentDictCodeAndValue("income", borrower.getIncome());
        String returnSource = dictService.getNameByParentDictCodeAndValue("returnSource", borrower.getReturnSource());
        String contactsRelation = dictService.getNameByParentDictCodeAndValue("relation", borrower.getContactsRelation());

        //设置下拉列表选中内容
        borrowerDetailVO.setEducation(education);
        borrowerDetailVO.setIndustry(industry);
        borrowerDetailVO.setIncome(income);
        borrowerDetailVO.setReturnSource(returnSource);
        borrowerDetailVO.setContactsRelation(contactsRelation);

        //加入附件信息集合
        List<BorrowerAttachVO> borrowerAttachVOList = borrowerAttachService.selectBorrowerAttachVOList(id);
        borrowerDetailVO.setBorrowerAttachVOList(borrowerAttachVOList);

        return borrowerDetailVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowerApprovalVO borrowerApprovalVO) {


        //借款人认证状态
        Long borrowerId = borrowerApprovalVO.getBorrowerId();
        Borrower borrower = baseMapper.selectById(borrowerId);
        borrower.setStatus(borrowerApprovalVO.getStatus());
        baseMapper.updateById(borrower);

        Long userId = borrower.getUserId();
        UserInfo userInfo = userInfoMapper.selectById(userId);


        //保存userIntegral
        Boolean isHouseOk = borrowerApprovalVO.getIsHouseOk();
        Boolean isCarOk = borrowerApprovalVO.getIsCarOk();
        Boolean isIdCardOk = borrowerApprovalVO.getIsIdCardOk();
        Integer infoIntegral = borrowerApprovalVO.getInfoIntegral();

        UserIntegral userIntegral = new UserIntegral();
        userIntegral.setUserId(userId);
        userIntegral.setIntegral(infoIntegral);
        userIntegral.setContent("借款人基本信息");
        userIntegralMapper.insert(userIntegral);

        //当前积分
        int curIntegral = userInfo.getIntegral() + borrowerApprovalVO.getInfoIntegral();
       //房产积分
        if (isHouseOk) {
            curIntegral += IntegralEnum.BORROWER_IDCARD.getIntegral();
            UserIntegral houseIntegral = new UserIntegral();
            houseIntegral.setUserId(userId);
            houseIntegral.setContent("房子积分");
            houseIntegral.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral());
            userIntegralMapper.insert(houseIntegral);
        }
        //车产积分
        if (isCarOk) {
            curIntegral += IntegralEnum.BORROWER_CAR.getIntegral();
            UserIntegral CarIntegral = new UserIntegral();
            CarIntegral.setUserId(userId);
            CarIntegral.setContent("车子积分");
            CarIntegral.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
            userIntegralMapper.insert(CarIntegral);
        }
        //身份证积分
        if (isIdCardOk) {
            curIntegral += IntegralEnum.BORROWER_IDCARD.getIntegral();
            UserIntegral IdCardIntegral = new UserIntegral();
            IdCardIntegral.setUserId(userId);
            IdCardIntegral.setContent("身份证积分");
            IdCardIntegral.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
            userIntegralMapper.insert(IdCardIntegral);
        }
        userInfo.setIntegral(curIntegral);
        //修改审核状态
        userInfo.setBorrowAuthStatus(borrowerApprovalVO.getStatus());
        userInfoMapper.updateById(userInfo);

    }


}
